<?php

namespace app\api\controller;

use app\common\model\Address;
use app\common\model\Admin;
use app\common\model\Group as G;
use app\common\model\Topic;
use app\common\model\User as U;
use think\facade\Db;
use think\facade\Request;
use \Firebase\JWT\JWT;
use bingher\sms\AliSms;

class User extends ApiBase
{
    // 不需要验证token的方法
    protected $middleware = [
        'app\api\middleware\Auth' => ['except' => ['adminLogin', "joinTopic","miniWxLogin", "list", "userInfoById", "userRuleList","search"]],
    ];

    //用户列表
    public function list()
    {
        $type = input("type"); // 0位普通用户 1为马甲虚拟用户
        $keyword = input("keyword");
        $status = input("status");

        if(empty($type)){
            $type = 0;
        }

        if(!empty($keyword)){
            $where[] = ["username","like","%$keyword%"];
        }

        if(!empty($status)){
            $where[] = ["status","=",$status];
        }

        $where[] = ["type","=",$type];

        $list = U::getList($where);
        return success($list);
    }

    //管理员列表
    public function adminList()
    {
        $list = Admin::select()->each(function ($item) {
            $item["group_name"] = Db::name("group")->where("group_id", $item["group_id"])->value("name");
            return $item;
        });

        return success($list);
    }

    //登录用户信息
    public function userInfo()
    {
        $uid = $this->uid;

        $userInfo = U::withoutField("group_id,openid,status,create_time")->find($uid);
        $userInfo["follow"] = Db::name("follow")->where("uid", $uid)->count();
        $userInfo["fans"] = Db::name("follow")->where("follow_uid", $uid)->count();
        $userInfo["post_num"] = Db::name("post")->where("uid", $uid)->count();

        return success($userInfo);
    }

    //根据UID查询用户信息
    public function userInfoById()
    {
        $uid = input("uid");

        $userInfo = U::withoutField("group_id,openid,status,create_time")->find($uid);
        $userInfo["follow"] = Db::name("follow")->where("uid", $uid)->count();
        $userInfo["fans"] = Db::name("follow")->where("follow_uid", $uid)->count();
        $userInfo["post_num"] = Db::name("post")->where("uid", $uid)->count();

        //是否关注
        $sessionUid = $this->uid;
        $userInfo["is_follow"] = false;

        if ($sessionUid) {
            $isFollow = Db::name("follow")->where(["uid" => $sessionUid, "follow_uid" => $uid])->find();
            if ($isFollow) {
                $userInfo["is_follow"] = true;
            }
        }
        //创建的圈子列表
        $userInfo["create_topic_list"] = Topic::getListAll(["topic.uid" => $uid]);
        return success($userInfo);
    }

    //管理员修改信息
    public function editAdmin()
    {
        $data = input("post.");
        $uid = $this->uid;
        $data["uid"] = $uid;

        $res = Admin::update($data);
        if ($res) {
            return notice("修改成功");
        }
        return error("修改失败");
    }

    //用户修改信息
    public function userInfoEdit()
    {
        $data = input("post.");
        $uid = $this->uid;
        $data["uid"] = $uid;

        if(!empty($data["username"])){
            $user = Db::name("user")->where("username",$data["username"])->find();
            if($user){
                return error("用户昵称已存在");
            }
        }

        $res = U::update($data);
        if ($res) {
            return notice("修改成功");
        }
        return error("修改失败");
    }

    //管理员登录
    public function adminLogin()
    {
        $data = Request::post(['username', 'password']);

        $userInfo = Admin::where($data)->find();

        if ($userInfo) {

            $update["uid"] = $userInfo->uid;
            $update["login_ip"] = request()->ip();
            $update["last_login_time"] = time();

            Admin::update($update);

            $userInfo->hidden(['create_time', 'password'])->toArray();
            $userInfo["token"] = self::signToken($userInfo);
            return success($userInfo, "登录成功");
        }

        return error("用户名或密码错误！");
    }

    //添加管理员
    public function adminAdd()
    {
        $data = input("post.");

        try {
            validate(\app\common\validate\Admin::class)->check($data);
        } catch (ValidateException $e) {
            return error($e->getError());
        }

        $data["password"] = md5($data["password"]);
        $user = Admin::create($data);
        if ($user) {
            return success($user, "添加成功");
        }
        return error("添加失败");
    }

    //编辑管理员
    public function saveUserInfo()
    {
        $data = input("post.");

        try {
            validate(\app\common\validate\Admin::class)->check($data);
        } catch (ValidateException $e) {
            return error($e->getError());
        }

        $data["password"] = md5($data["password"]);
        $user = Admin::update($data);
        if ($user) {
            return success($user, "保存成功");
        }
        return error("保存失败");
    }

    //删除管理员
    public function delAdmin()
    {
        $uid = input("uid");

        if ($uid == 1) {
            return json(["code" => 0, "msg" => "默认管理员账号，不可删除"]);
        }

        if ($uid == $this->uid) {
            return json(["code" => 0, "msg" => "当前登录用户，不可删除"]);
        }

        $del = Admin::destroy($uid);
        if ($del) {
            return notice("删除成功");
        }
        return error("删除失败");
    }

    //小程序登录
    public function miniWxLogin()
    {
        $data = input("post.");

        $APPID = $this->APPID;
        $SECRET = $this->SECRET;

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $APPID . "&secret=" . $SECRET . "&js_code=" . $data["code"] . "&grant_type=authorization_code";

        $http = httpRequest($url);

        $openId = $http["openid"];

        $data["openid"] = $openId;
        $data["group_id"] = 2;
        $data["tag_str"] = [
            "云圈新人"
        ];

        $userInfo = Db::name("user")->where("openid", $openId)->find();


        if ($userInfo) {
            U::update(["uid" => $userInfo["uid"],"last_login_ip" => request()->ip()]);

            $token = self::signToken($userInfo);

            return success(["token" => $token], "登录成功");
        } else {

            //防止用户名重复
            $user = Db::name("user")->where("username",$data["username"])->find();
            if($user){
                $data["username"] = $data["username"] .rand(1000000,9999999);
            }

            $user = U::create($data);
            if ($user) {
                $token = self::signToken(["uid" => $user->uid]);
                return success(["token" => $token], "登录成功");
            }
        }

        return error("登录失败");
    }

    //生成token
    public static function signToken($userInfo)
    {
        $key = constant("token_key"); //这里是自定义的一个随机字串，解密时也会用
        $token = array(
            "iss" => $key, //签发者 可以为空
            "aud" => '', //面象的用户，可以为空
            "iat" => time(), //签发时间
            "nbf" => time() + 3, //在什么时候jwt开始生效
            "exp" => time() + 604800, //token 过期时间 七天后失效
            "data" => $userInfo,
        );

        $jwt = JWT::encode($token, $key, "HS256");
        return $jwt;
    }

    //我的关注
    public function follow()
    {
        $uid = $this->uid;
        $followUids = Db::name("follow")->where("uid", $uid)->column("follow_uid");
        $list = U::where("uid", "in", $followUids)->withoutField("password,email,group_id,openid,status,user_type,create_time")->paginate(10)->each(function ($item) {
            $where["uid"] = $item["uid"];
            $where["follow_uid"] = $this->uid;

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $item["has_follow"] = 1; //互相关注
            } else {
                $item["has_follow"] = 2; //已关注
            }

            return $item;
        });
        return success($list);
    }

    //我的粉丝(即将废弃)
    public function fans()
    {
        $uid = $this->uid;
        $fansUids = Db::name("follow")->where("follow_uid", $uid)->column("uid");
        $list = U::where("uid", "in", $fansUids)->withoutField("password,email,group_id,openid,status,user_type,create_time")->paginate(10, false, ['query' => request()->param()])->each(function ($item, $key) {
            $where["uid"] = $this->uid;
            $where["follow_uid"] = $item["uid"];

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $item["has_follow"] = 1; //互相关注
            } else {
                $item["has_follow"] = 0; //未关注
            }

            return $item;
        });
        return success($list);
    }

    //我的粉丝
    public function userFans(){
        $uid = $this->uid;
        $list = Db::name("follow")->where("follow_uid", $uid)->order("create_time desc")->paginate(20)->each(function ($item){
            $user = U::where("uid",  $item["uid"])->find();

            $where["uid"] = $this->uid;
            $where["follow_uid"] = $user["uid"];

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $user["has_follow"] = 1; //互相关注
            } else {
                $user["has_follow"] = 0; //未关注
            }

            return $user;
        });

        return success($list);
    }
    //添加关注
    public function addFollow()
    {
        $id = input("id");
        $uid = $this->uid;
        if ($id == $uid) {
            return json(["code" => 0, "msg" => "不能关注自己"]);
        }
        $find = Db::name("follow")->where(["uid" => $uid, "follow_uid" => $id])->find();
        if ($find) {
            return json(["code" => 0, "msg" => "请勿重复关注"]);
        }
        $res = Db::name("follow")->insert(["uid" => $uid, "follow_uid" => $id,"create_time" => time()]);
        $username = Db::name("user")->where("uid", $uid)->value("username");
        if ($res) {
            $this->sendMsg($uid, $id, 0, 4, "【" . $username . "】关注了你");
            return notice("关注成功");
        }
        return error("关注失败");
    }

    //取消关注
    public function cancelFollow()
    {
        $id = input("id");
        $uid = $this->uid;

        $where["uid"] = $uid;
        $where["follow_uid"] = $id;
        $res = Db::name("follow")->where($where)->delete();
        if ($res) {
            return notice("已取消关注");
        }
        return error("错误");
    }

    //用户组列表
    public function adminRole()
    {
        $list = G::select();
        return success($list);
    }

    //添加和修改用户组
    public function addRole()
    {
        $roleName = input("roleName");
        $id = input("id");
        if (empty($roleName)) {
            return json(["code" => 0, "msg" => "角色名不能为空"]);
        }
        if (empty($id)) {
            $addRole = G::create(["name" => $roleName]);
            if ($addRole) {
                return notice("添加成功");
            }
            return error("添加失败");
        } else {
            $updateRole = G::update(["name" => $roleName], ["group_id" => $id]);
            if ($updateRole) {
                return notice("修改成功");
            }
            return error("修改失败");
        }
    }

    //删除用户组
    public function delGroup()
    {
        $id = input("id");
        if ($id == 1 || $id == 2) {
            return json(["code" => 0, "msg" => "系统默认用户组不可删除"]);
        }
        $del = Db::name("group")->where("group_id", $id)->delete();
        if ($del) {
            return notice("删除成功");
        }
        return error("删除失败");
    }

    //用户组权限
    public function groupRule()
    {
        $id = input("id");
        if (!empty($id)) {
            //用户组拥有的权限
            $ruleIdList = Db::name("group_rule")->where("group_id", $id)->column("rule_id");
            return success($ruleIdList);
        } else {

            //列出所有权限
            $ruleIdList = Db::name("rule")->column("id");
            $ruleList = array();
            foreach ($ruleIdList as $item) {
                $ruleItem = Db::name("rule")->withoutField("name")->where("id", $item)->find();
                $ruleList[$ruleItem["pid"]][] = $ruleItem;
            }
            return success($ruleList);
        }
    }

    //修改用户组权限
    public function saveRule()
    {
        $groupId = input("groupId");
        $ruleIdList = input("post.ruleIdList/a");

        if ($groupId == 1) {
            return json(["code" => 0, "msg" => "不能修改超级管理员权限"]);
        }

        $isGroupRule = Db::name('group_rule')->where('group_id', $groupId)->find();
        if ($isGroupRule) {
            $delGroup = Db::name('group_rule')->where('group_id', $groupId)->delete();
            if (!$delGroup) {
                return json(["code" => 0, "msg" => "权限修改失败了"]);
            }
        }
        foreach ($ruleIdList as $ruleId) {

            $data["group_id"] = $groupId;
            $data["rule_id"] = $ruleId;

            $pid = Db::name("rule")->where("id", $ruleId)->value("pid");
            $isRule = Db::name("group_rule")->where(["group_id" => $groupId, "rule_id" => $pid])->find();

            if ($pid > 0 && !$isRule) {
                Db::name("group_rule")->insert(["group_id" => $groupId, "rule_id" => $pid]);
            }
            $createRule = Db::name("group_rule")->insert($data);
            if (!$createRule) {
                return error("权限修改失败");
            }

        }
        return notice("权限修改成功");
    }

    //删除用户
    public function delUser()
    {
        $uid = input("uid");

        $del = U::destroy($uid);
        if ($del) {
            return notice("删除成功");
        }
        return error("删除失败");
    }

    //修改用户状态
    public function userStatus()
    {
        $status = input("status");
        $uid = input("uid");
        $rel = U::update(["status" => $status], ["uid" => $uid]);
        if ($rel) {
            return notice("状态修改成功");
        }
        return error("状态修改失败");
    }

    //用户地址列表
    public function addressList()
    {
        $uid = $this->uid;
        $list = Db::name("address")->where("uid", $uid)->select();

        return success($list);
    }

    //地址详情
    public function addressInfo()
    {
        $id = input("address_id");
        $info = Db::name("address")->where("id", $id)->find();
        return success($info);
    }

    //设置默认地址
    public function setAddressEdit()
    {

        $where["id"] = input("address_id");
        $where["uid"] = $this->uid;

        Address::where(["uid" => $this->uid, "is_default" => 1])->update(["is_default" => 0]);

        $res = Db::name("address")->where($where)->update(["is_default" => 1]);

        if ($res) {
            return notice("修改成功");
        }

        return error("修改失败");
    }

    //编辑地址
    public function addressEdit()
    {
        $data = input("post.");
        $res = Address::update($data);

        if ($res) {
            return notice("保存成功");
        }

        return error("保存失败");
    }

    //新增地址
    public function addressAdd()
    {
        $data = input("post.");
        $data["uid"] = $this->uid;
        $res = Address::create($data);

        if ($res) {
            return notice("保存成功");
        }

        return error("保存失败");
    }

    //角色列表
    public function roleList()
    {
        $list = Db::name("group")->select();
        return success($list);
    }

    //添加管理员角色
    public function roleAdd()
    {
        $data = input("post.");
        $data["create_time"] = time();
        $res = Db::name("group")->insert($data);
        if ($res) {
            return notice("添加成功");
        }

        return error("添加失败");
    }

    //删除角色
    public function roleDel()
    {
        $id = input("post.id");
        $res = Db::name("group")->where("group_id", $id)->delete();
        if ($res) {
            return notice("删除成功");
        }

        return error("删除失败");
    }

    //角色权限列表
    public function roleRuleList()
    {
        $id = input("id");

        $ruleUserIds = Db::name("group_rule")->where("group_id", $id)->column("rule_id");
        $ruleAll = Db::name("rule")->select()->each(function ($item, $key) use ($ruleUserIds) {
            if (in_array($item["id"], $ruleUserIds)) {
                $item["is_own"] = true;
            } else {
                $item["is_own"] = false;
            }

            return $item;
        });
        $treeRule["all_rule"] = makeTree($ruleAll);
        $treeRule["user_rule_ids"] = $ruleUserIds;
        return success($treeRule);
    }

    //保存角色权限
    public function userRuleSave()
    {
        $ruleIds = input("rule_ids");
        $roleId = input("role_id");
        $data = [];

        foreach ($ruleIds as $id) {
            array_push($data, ["group_id" => $roleId, "rule_id" => $id]);
        }

        Db::name("group_rule")->where("group_id", $roleId)->delete();

        if (!empty($data)) {
            $res = Db::name("group_rule")->insertAll($data);
            if ($res) {
                return notice("保存成功");
            }
            return error("保存失败");
        } else {
            return notice("保存成功");
        }
    }

    //登录用户菜单列表
    public function userRuleList()
    {
        $uid = $this->uid;
        $groupId = Admin::where("uid", $uid)->value("group_id");

        $ruleIds = Db::name("group_rule")->where("group_id", $groupId)->column("rule_id");
        $userRule = Db::name("rule")->where("is_menu", 1)->where("id", "in", $ruleIds)->select();

        $treeRule = makeTree($userRule);

        return success($treeRule);
    }

    //更新用户fd
    public function saveUserFd()
    {
        $uid = $this->uid;
        $fd = input("fd");
        $res = U::update(["fd" => $fd], ["uid" => $uid]);
        return notice("更新fd成功");
    }

    //获取用户对话聊天消息
    public function chatList()
    {
        $toUid = input("uid");
        $fromUid = $this->uid;

        $where1["to_uid"] = $toUid;
        $where1["from_uid"] = $fromUid;

        $where2["to_uid"] = $fromUid;
        $where2["from_uid"] = $toUid;

        $toList = Db::name("message")->where("type", 6)->where($where1)->select()->toArray();
        $fromList = Db::name("message")->where("type", 6)->where($where2)->select()->toArray();

        $list = array_merge($toList, $fromList); //合并数组
        $temps = array_column($list, 'm_id');

        array_multisort($list, SORT_ASC, $temps);

        return success($list);
    }

    //发送聊天消息
    public function sendMessage()
    {

        $from_uid = $this->uid;
        $to_uid = input("uid");
        $content = input("content");

        $this->sendMsg($from_uid, $to_uid, 0, 6, $content);

        return notice("发送成功");
    }

    //添加马甲用户
    public function vestAdd(){
        $data = input("post.");
        $data["type"] = 2;
        $res = U::create($data);
        if ($res){
            return notice("添加成功");
        }
        return  error("添加失败");
    }

    //马甲用户关注
    public function vestUserFollow(){
        $followUid = input("follow_uid");
        $uids = input("uids");

        $success = true;
        foreach ($uids as $uid){

            $data["uid"] = $uid;
            $data["follow_uid"] = $followUid;

            $res = Db::name("follow")->insert($data);

            $username = Db::name("user")->where("uid", $uid)->value("username");
            $this->sendMsg($uid, $followUid, 0, 4, "【" . $username . "】关注了你");

            if(!$res){
                $success = false;
            }
        }

        if($success){
            return notice("操作成功");
        }
        return error("发生错误");
    }

    //搜索
    public function search(){
        $keyword = input("keyword");
        $where[] = ["username","like","%$keyword%"];
        $list = U::getList($where);
        return success($list);
    }

    //让用户加入某个圈子
//    public function joinTopic(){
//        $uids = Db::name("user")->column("uid");
//
//        foreach ( $uids as $uid){
//            $where["uid"] = $uid;
//            $where["topic_id"] = 272;
//            $isJoin =  Db::name("user_topic")->where($where)->find();
//            if(!$isJoin){
//                Db::name("user_topic")->insert($where);//加入云圈官方圈子
//            }
//        }
//    }
}
